import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Button,
  Input,
  Select,
  Space,
  Typography,
  Form,
  message,
  List,
  Tag,
  Modal,
  Progress,
  Divider,
} from 'antd';
import {
  SearchOutlined,
  UserOutlined,
  HeartOutlined,
  SendOutlined,
  SwapOutlined,
} from '@ant-design/icons';
import { User } from '@/types';
import { getAvatarUrl } from '@/utils';

const { Title, Text } = Typography;
const { TextArea } = Input;

const MatchOperation: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [selectedUserA, setSelectedUserA] = useState<User | null>(null);
  const [selectedUserB, setSelectedUserB] = useState<User | null>(null);
  const [userSearchResults, setUserSearchResults] = useState<User[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [matchModalVisible, setMatchModalVisible] = useState(false);
  const [form] = Form.useForm();

  // Mock users data
  const mockUsers: User[] = [
    {
      id: '1',
      nickname: '李小花',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
      age: 26,
      gender: 'female',
      education: '本科',
      occupation: '设计师',
      city: '北京',
      profileStatus: 'approved',
      registerTime: '2024-01-15T10:30:00Z',
      lastLoginTime: '2024-01-20T14:25:00Z',
      isVip: true,
      tags: ['旅行', '摄影', '美食'],
      introduction: '热爱生活的设计师',
      photos: [],
    },
    {
      id: '2',
      nickname: '王明',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
      age: 28,
      gender: 'male',
      education: '硕士',
      occupation: '工程师',
      city: '北京',
      profileStatus: 'approved',
      registerTime: '2024-01-14T09:15:00Z',
      lastLoginTime: '2024-01-19T16:45:00Z',
      isVip: false,
      tags: ['运动', '科技', '电影'],
      introduction: '程序员，喜欢运动',
      photos: [],
    },
  ];

  const searchUsers = async (query: string) => {
    setLoading(true);
    // Simulate API call
    setTimeout(() => {
      const filtered = mockUsers.filter(user =>
        user.nickname.includes(query) ||
        user.occupation.includes(query) ||
        user.city.includes(query)
      );
      setUserSearchResults(filtered);
      setLoading(false);
    }, 500);
  };

  const calculateMatchScore = (userA: User, userB: User): number => {
    let score = 0;
    
    // Age compatibility (30%)
    const ageDiff = Math.abs(userA.age - userB.age);
    if (ageDiff <= 3) score += 30;
    else if (ageDiff <= 5) score += 20;
    else if (ageDiff <= 8) score += 10;

    // Location (20%)
    if (userA.city === userB.city) score += 20;

    // Education (20%)
    if (userA.education === userB.education) score += 20;
    else if (Math.abs(['高中', '大专', '本科', '硕士', '博士'].indexOf(userA.education) - 
                     ['高中', '大专', '本科', '硕士', '博士'].indexOf(userB.education)) <= 1) score += 15;

    // Common interests (30%)
    const commonTags = userA.tags?.filter(tag => userB.tags?.includes(tag)) || [];
    score += Math.min(commonTags.length * 10, 30);

    return Math.min(score, 100);
  };

  const handleCreateMatch = () => {
    if (!selectedUserA || !selectedUserB) {
      message.warning('请先选择两个用户');
      return;
    }

    if (selectedUserA.id === selectedUserB.id) {
      message.warning('不能选择同一个用户');
      return;
    }

    const matchScore = calculateMatchScore(selectedUserA, selectedUserB);
    form.setFieldsValue({
      userAId: selectedUserA.id,
      userBId: selectedUserB.id,
      matchScore,
      recommendation: `基于人工分析，${selectedUserA.nickname}和${selectedUserB.nickname}在年龄、地域、兴趣等方面较为匹配，建议进行牵线尝试。`,
    });
    setMatchModalVisible(true);
  };

  const handleSubmitMatch = async (values: any) => {
    try {
      setLoading(true);
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success('手动匹配创建成功');
      setMatchModalVisible(false);
      form.resetFields();
      setSelectedUserA(null);
      setSelectedUserB(null);
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    searchUsers('');
  }, []);

  return (
    <div className="page-container">
      <div className="page-header">
        <Title level={4} className="page-title">牵线操作</Title>
        <Text className="page-description">
          手动为用户进行匹配推荐，支持个性化匹配策略
        </Text>
      </div>

      <Row gutter={[24, 24]}>
        {/* User Search */}
        <Col xs={24} lg={12}>
          <Card title="用户搜索" style={{ height: '600px' }}>
            <Input
              placeholder="搜索用户昵称、职业或城市"
              prefix={<SearchOutlined />}
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                searchUsers(e.target.value);
              }}
              style={{ marginBottom: '16px' }}
            />
            
            <List
              loading={loading}
              dataSource={userSearchResults}
              renderItem={(user) => (
                <List.Item
                  actions={[
                    <Button
                      size="small"
                      onClick={() => setSelectedUserA(user)}
                      disabled={selectedUserA?.id === user.id}
                    >
                      选为用户A
                    </Button>,
                    <Button
                      size="small"
                      onClick={() => setSelectedUserB(user)}
                      disabled={selectedUserB?.id === user.id}
                    >
                      选为用户B
                    </Button>,
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        src={getAvatarUrl(user.avatar, user.gender)}
                        icon={<UserOutlined />}
                      />
                    }
                    title={
                      <Space>
                        {user.nickname}
                        {user.isVip && <Tag color="gold">VIP</Tag>}
                      </Space>
                    }
                    description={
                      <div>
                        <Text type="secondary">
                          {user.age}岁 • {user.gender === 'male' ? '男' : '女'} • {user.city}
                        </Text>
                        <br />
                        <Text type="secondary">
                          {user.education} • {user.occupation}
                        </Text>
                        <br />
                        <Space wrap>
                          {user.tags?.slice(0, 3).map((tag, index) => (
                            <Tag key={index} size="small">{tag}</Tag>
                          ))}
                        </Space>
                      </div>
                    }
                  />
                </List.Item>
              )}
              style={{ height: '500px', overflow: 'auto' }}
            />
          </Card>
        </Col>

        {/* Match Preview */}
        <Col xs={24} lg={12}>
          <Card title="匹配预览" style={{ height: '600px' }}>
            <div style={{ textAlign: 'center', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              {/* User A */}
              <div>
                <Title level={5}>用户A</Title>
                {selectedUserA ? (
                  <div>
                    <Avatar
                      size={80}
                      src={getAvatarUrl(selectedUserA.avatar, selectedUserA.gender)}
                      icon={<UserOutlined />}
                    />
                    <div style={{ marginTop: '12px' }}>
                      <Text strong>{selectedUserA.nickname}</Text>
                      <br />
                      <Text type="secondary">
                        {selectedUserA.age}岁 • {selectedUserA.gender === 'male' ? '男' : '女'}
                      </Text>
                      <br />
                      <Text type="secondary">
                        {selectedUserA.education} • {selectedUserA.occupation}
                      </Text>
                      <br />
                      <Text type="secondary">{selectedUserA.city}</Text>
                    </div>
                  </div>
                ) : (
                  <div style={{ padding: '40px 0', border: '2px dashed #d9d9d9', borderRadius: '8px' }}>
                    <UserOutlined style={{ fontSize: '48px', color: '#d9d9d9' }} />
                    <div style={{ marginTop: '12px' }}>
                      <Text type="secondary">请选择用户A</Text>
                    </div>
                  </div>
                )}
              </div>

              {/* Match Icon & Score */}
              <div style={{ margin: '20px 0' }}>
                <SwapOutlined style={{ fontSize: '24px', color: '#1890ff' }} />
                {selectedUserA && selectedUserB && (
                  <div style={{ marginTop: '8px' }}>
                    <Progress
                      type="circle"
                      percent={calculateMatchScore(selectedUserA, selectedUserB)}
                      size={60}
                      format={(percent) => `${percent}%`}
                    />
                    <div style={{ marginTop: '4px' }}>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        匹配度
                      </Text>
                    </div>
                  </div>
                )}
              </div>

              {/* User B */}
              <div>
                <Title level={5}>用户B</Title>
                {selectedUserB ? (
                  <div>
                    <Avatar
                      size={80}
                      src={getAvatarUrl(selectedUserB.avatar, selectedUserB.gender)}
                      icon={<UserOutlined />}
                    />
                    <div style={{ marginTop: '12px' }}>
                      <Text strong>{selectedUserB.nickname}</Text>
                      <br />
                      <Text type="secondary">
                        {selectedUserB.age}岁 • {selectedUserB.gender === 'male' ? '男' : '女'}
                      </Text>
                      <br />
                      <Text type="secondary">
                        {selectedUserB.education} • {selectedUserB.occupation}
                      </Text>
                      <br />
                      <Text type="secondary">{selectedUserB.city}</Text>
                    </div>
                  </div>
                ) : (
                  <div style={{ padding: '40px 0', border: '2px dashed #d9d9d9', borderRadius: '8px' }}>
                    <UserOutlined style={{ fontSize: '48px', color: '#d9d9d9' }} />
                    <div style={{ marginTop: '12px' }}>
                      <Text type="secondary">请选择用户B</Text>
                    </div>
                  </div>
                )}
              </div>

              {/* Action Button */}
              <div style={{ marginTop: '24px' }}>
                <Button
                  type="primary"
                  size="large"
                  icon={<HeartOutlined />}
                  onClick={handleCreateMatch}
                  disabled={!selectedUserA || !selectedUserB}
                >
                  创建匹配
                </Button>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* Match Modal */}
      <Modal
        title="确认创建匹配"
        open={matchModalVisible}
        onCancel={() => setMatchModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmitMatch}
        >
          <Form.Item name="userAId" hidden>
            <Input />
          </Form.Item>
          <Form.Item name="userBId" hidden>
            <Input />
          </Form.Item>
          
          <Form.Item
            label="匹配评分"
            name="matchScore"
          >
            <Input disabled suffix="%" />
          </Form.Item>
          
          <Form.Item
            label="推荐理由"
            name="recommendation"
            rules={[{ required: true, message: '请输入推荐理由' }]}
          >
            <TextArea
              rows={4}
              placeholder="请输入匹配推荐理由，将发送给双方用户"
            />
          </Form.Item>
          
          <Form.Item
            label="内部备注"
            name="notes"
          >
            <TextArea
              rows={2}
              placeholder="内部备注（用户不可见）"
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确认创建
              </Button>
              <Button onClick={() => setMatchModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MatchOperation;